<template>
	<div class="container">
		<el-row>
			<el-col :span="24">
				<h1 v-html="`${question.id}. ${removeOuterPTags(question.stem)}`">
				  
				</h1>
				<span class="question-mark" :class="getQuestionMarkClass(question.id)" @click.stop="toggleQuestionMark(question.id)"></span>
				<el-form ref="questionForm">
					<el-radio-group v-if="question.type !== '多选题'" v-model="selectedAnswer">
						<el-radio v-for="(option, index) in question.options" :label="getLabel(index)" :key="index">
							<span>{{ getLabel(index) }}.</span>
							<span v-html="removeOuterPTags(option)"></span>
						</el-radio>
					</el-radio-group>
					<el-checkbox-group v-else v-model="selectedAnswers">
						<el-checkbox v-for="(option, index) in question.options" :label="getLabel(index)" :key="index">
							<span>{{ getLabel(index) }}.</span>
							<span v-html="removeOuterPTags(option)"></span>
						</el-checkbox>
					</el-checkbox-group><br>
					<el-button type="primary" @click="submitAnswer">Submit</el-button>
					<el-button style="margin-left: 0;" @click="gotoQuestion(question.id + 1)">Next</el-button>
					<el-button style="margin-left: 0;" @click="gotoQuestion(question.id - 1)">Prev</el-button>
				</el-form>

				<div v-if="result" class="result-card">
					<el-card :class="{'correct-card': result === 'Correct', 'incorrect-card': result !== 'Correct'}">
						<div class="result-content">
							<h3>Result: {{ result }}</h3>
							<p>Correct Answer: {{ correctAnswer }}</p>
						</div>
					</el-card>
				</div>
				<!-- <div v-if="result" :class="{'correct': result === 'Correct', 'incorrect': result !== 'Correct'}">
					Result: {{ result }}<br>
					Correct Answer: {{ correctAnswer }}
				</div> -->
				<!-- 新增按钮和弹出框 -->
				<el-button type="text" @click="showQuestionsDialog = true">Show All Questions</el-button>
				<el-dialog title="All Questions" :visible.sync="showQuestionsDialog">
					<el-list>
						<el-list-item class="popup-item" v-for="i in totalQuestions" :key="i" @click="gotoQuestion(i)"
							:style="getQuestionStyle(i)">
							{{ i }}
						</el-list-item>
					</el-list>
					<div style="margin-top: 10px;">
						<el-button type="danger" @click="resetCompletedQuestions">重置</el-button>
						<el-button type="infor" @click="exportWrongQuestions">导出错题</el-button>
					</div>
				</el-dialog>



			</el-col>
		</el-row>
	</div>
</template>

<script>
	import axios from 'axios';
	export default {
		props: ['id'],
		data() {
			return {
				question: {}, // You need to populate this from your API
				answeredQuestions: {},
				// ...其他数据...
				    questionMarks: JSON.parse(localStorage.getItem('questionMarks')) || {},
				selectedAnswer: '',
				selectedAnswers: [],
				result: '',
				correctAnswer: '',
				showQuestionsDialog: false,
				totalQuestions: 400 ,// 假设您有400个问题
				// ...其他数据...
				        answeredQuestions: JSON.parse(localStorage.getItem('answeredQuestions')) || {},
				        completedQuestions: JSON.parse(localStorage.getItem('completedQuestions')) || {}
				 
			};
		},
		methods: {
			getQuestionMarkClass(questionId) {
			    if (this.questionMarks[questionId] === true) {
			      return 'mark-red';
			    } else if (this.completedQuestions[questionId] === true) {
			      return 'mark-green';
			    } else if (this.completedQuestions[questionId] === false) {
			      return 'mark-red';
			    }
			    return 'mark-gray';
			  },
			
  toggleQuestionMark(questionId) {
    let completed = JSON.parse(localStorage.getItem('completedQuestions')) || {};
  
    // 如果题目已经存在于完成列表中，则将其状态取反；否则默认标记为错误
    if (completed.hasOwnProperty(questionId)) {
      completed[questionId] = !completed[questionId];
    } else {
      completed[questionId] = false;
    }
  
    // 更新 localStorage
    localStorage.setItem('completedQuestions', JSON.stringify(completed));
  
    // 使用 Vue.set 来更新 completedQuestions，确保 Vue 能够检测到变化
    this.$set(this.completedQuestions, questionId, completed[questionId]);
  },
			removeOuterPTags(text) {
				// 正则表达式匹配最外层的 <p> 标签
				const regex = /^<p>(.*)<\/p>$/i;
				const match = regex.exec(text);

				// 如果匹配到了，返回匹配的内容部分，否则返回原文本
				return match ? match[1] : text;
			},
			exportWrongQuestions() {
			        let completed = JSON.parse(localStorage.getItem('completedQuestions')) || {};
			        let answeredQuestions = JSON.parse(localStorage.getItem('answeredQuestions')) || {};
			        
			        // 生成错题列表
			        let wrongQuestionsText = Object.keys(completed)
			            .filter(id => !completed[id])
			            .map(id => {
			                let question = answeredQuestions[id];
			                if (!question) return ''; // 如果没有这个题目的信息，跳过
			
			                return `题目 ${id}: ${question.stem}\n` +
			                       `选项: ${question.options.join(', ')}\n` +
			                       `您的答案: ${Array.isArray(question.userAnswer) ? question.userAnswer.join(', ') : question.userAnswer}\n` +
			                       `正确答案: ${question.correctAnswer}\n\n`;
			            })
			            .join(''); // 将所有错题信息合并为一个字符串
			
			        if (!wrongQuestionsText) {
			            alert("没有错题可导出");
			            return;
			        }
			
			        // 创建 Blob 对象，用于生成文件
			        const blob = new Blob([wrongQuestionsText], { type: 'text/plain' });
			
			        // 创建下载链接
			        const url = URL.createObjectURL(blob);
			        const a = document.createElement('a');
			        a.href = url;
			        a.download = 'wrong-questions.txt'; // 设定下载文件名
			        document.body.appendChild(a);
			        a.click();
			        document.body.removeChild(a);
			
			        // 释放 URL 对象
			        URL.revokeObjectURL(url);
			    },


			createDownloadLink(text, filename) {
				const blob = new Blob([text], {
					type: 'text/plain'
				});
				const url = URL.createObjectURL(blob);
				const a = document.createElement('a');
				a.href = url;
				a.download = filename;
				a.click();
				URL.revokeObjectURL(url);
			},


			resetCompletedQuestions() {
				localStorage.removeItem('completedQuestions');
				this.$forceUpdate(); // 强制更新组件以反映更改
			},
			getQuestionStyle(questionId) {
				let completed = JSON.parse(localStorage.getItem('completedQuestions')) || {};
				if (completed.hasOwnProperty(questionId)) {
					return {
						color: completed[questionId] ? '#67c23a' : '#f56c6c' // 绿色表示正确，红色表示错误
					};
				}
				return {};
			},

			getLabel(index) {
				return ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'][index];
			},
			submitAnswer() {
				// Implement the logic to submit the answer to your Express server
				// Update `result` and `correctAnswer` based on the response
			},
			gotoQuestion(id) {
				// 更新当前组件的 id，然后重新加载数据
				this.$router.push({
					name: 'question',
					params: {
						id: id
					}
				}).catch(err => {});
				this.showQuestionsDialog = false;
				this.$nextTick(() => {
					this.fetchQuestionData();
				});
			},
			// 在 methods 中
			submitAnswer() {
			  let data = this.question.type === '多选题' ? {
			    answers: this.selectedAnswers
			  } : {
			    answer: this.selectedAnswer
			  };
			
			  axios.post(`https://www.seedstudio.cn:3001/practice/submit/${this.question.id}`, data)
			    .then(response => {
			      this.result = response.data.result;
			      this.correctAnswer = response.data.correctAnswer;
			
			      // 更新答题状态和 localStorage
			      let completed = JSON.parse(localStorage.getItem('completedQuestions')) || {};
			      completed[this.question.id] = this.result === 'Correct';
			      localStorage.setItem('completedQuestions', JSON.stringify(completed));
			
			      // 使用 Vue.set 来确保更新视图
			      this.$set(this.completedQuestions, this.question.id, this.result === 'Correct');
			    })
			    .catch(error => {
			      console.error(error);
			      // Handle error
			    });
			
			  // 保存题目详情
			  let answeredQuestions = JSON.parse(localStorage.getItem('answeredQuestions')) || {};
			  answeredQuestions[this.question.id] = {
			    stem: this.question.stem,
			    options: this.question.options,
			    correctAnswer: this.correctAnswer,
			    userAnswer: this.question.type === '多选题' ? this.selectedAnswers : this.selectedAnswer
			  };
			  localStorage.setItem('answeredQuestions', JSON.stringify(answeredQuestions));
			},


			fetchQuestionData() {
				axios.get(`https://www.seedstudio.cn:3001/practice/question/${this.$route.params.id}`)
					.then(response => {
						this.question = response.data;
						this.selectedAnswer = '';
						this.selectedAnswers = [];
						this.result = '';
						this.correctAnswer = '';
					})
					.catch(error => {
						console.error(error);
						// 错误处理...
					});
			},
			handleKeyDown(e) {
				// 左箭头键切换到上一题
				if (e.keyCode === 37) { // 37 是左箭头键的键码
					this.gotoQuestion(this.question.id - 1);
				}

				// 右箭头键切换到下一题
				if (e.keyCode === 39) { // 39 是右箭头键的键码
					this.gotoQuestion(this.question.id + 1);
				}

				// 数字键选择选项
				if (e.keyCode >= 49 && e.keyCode <= 53) { // 49-53 是数字键 1-5 的键码
					const optionIndex = e.keyCode - 49; // 将键码转换为选项索引
					this.toggleOption(optionIndex);
				}

				// 回车键或空格键提交答案
				if (e.keyCode === 13 || e.keyCode === 32) { // 13 是回车键，32 是空格键
					this.submitAnswer();
				}

			},

			toggleOption(index) {
				// 确保索引在选项范围内
				if (index < this.question.options.length) {
					const optionLabel = this.getLabel(index);

					// 对于单选题，直接设置选中的答案
					if (this.question.type !== '多选题') {
						this.selectedAnswer = optionLabel;
					} else {
						// 对于多选题，切换选项的选中状态
						const selectedIdx = this.selectedAnswers.indexOf(optionLabel);
						if (selectedIdx >= 0) {
							this.selectedAnswers.splice(selectedIdx, 1); // 如果已选中，则取消选中
						} else {
							this.selectedAnswers.push(optionLabel); // 如果未选中，则选中
						}
					}
				}
			},
			loadCompletedQuestions() {
			    let completed = JSON.parse(localStorage.getItem('completedQuestions')) || {};
			    this.completedQuestions = completed;
			  },
		},
		created() {
			this.fetchQuestionData();
			this.loadCompletedQuestions(); // 新增函数调用
		},
		mounted() {
			document.addEventListener('keydown', this.handleKeyDown);
		},

		beforeDestroy() {
			document.removeEventListener('keydown', this.handleKeyDown);
		},
	};
</script>

<style scoped>
	.question-mark {
	    display: inline-block;
	    width: 10px;
	    height: 10px;
	    border-radius: 3px;
	    margin-left: 5px;
	    cursor: pointer;
	  }
	
	  .mark-gray {
	    background-color: lightgray;
	  }
	
	  .mark-green {
	    background-color: seagreen;
	  }
	
	  .mark-red {
	    background-color: deeppink;
	  }
	.button-group {
		margin-bottom: 20px;
		text-align: center;
	}

	.button-group .el-button {
		margin: 0 10px;
	}

	.popup-item {
		padding: 2px;
		border: 1px solid #e5e5e5;
		border-radius: 4px;
		margin: 4px;
		display: inline-block;
		width: 25px;
		text-align: center;
		color: #999;
	}

	/* 其他样式... */

	.result-card {
		margin-top: 20px;
	}

	.correct-card {
		border-left: 5px solid #67c23a;
		/* 添加左边框以区分正确结果 */
	}

	.incorrect-card {
		border-left: 5px solid #f56c6c;
		/* 添加左边框以区分错误结果 */
	}

	.result-content h3 {
		color: #333;
		/* 标题颜色 */
	}

	.result-content p {
		color: #666;
		/* 正文颜色 */
	}

	/* 其他样式... */

	@media (max-width: 600px) {
		.result-card {
			margin-top: 15px;
		}

		.correct-card,
		.incorrect-card {
			border-left-width: 3px;
			/* 在小屏幕上减小边框宽度 */
		}
	}

	.el-radio,
	.el-checkbox {
		font-size: 16px;
		/* 增大字体大小 */
		margin-bottom: 10px;
		/* 增加间距 */
		line-height: 1.5;
		/* 调整行高 */
		white-space: normal;
		/* 允许换行 */
	}

	.el-radio .el-radio__label,
	.el-checkbox .el-checkbox__label {
		white-space: normal;
		/* 允许标签内容换行 */
	}

	@media (max-width: 600px) {

		.el-radio,
		.el-checkbox {
			font-size: 14px;
			/* 在小屏幕上减小字体大小 */
			margin-bottom: 15px;
			/* 增加更多的间距 */
		}
	}

	.container {
		box-sizing: border-box;
		max-width: 800px;
		margin: auto;
		padding: 20px;
		background-color: #fff;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	}

	h1 {
		font-size: 24px;
		color: #333;
	}

	.el-radio-group,
	.el-checkbox-group {
		margin: 15px 0;
	}

	.el-button {
		margin-right: 10px;
	}

	.result {
		margin-top: 20px;
		padding: 10px;
		border-radius: 4px;
	}

	.correct {
		background-color: #e1f3d8;
		color: #67c23a;
	}

	.incorrect {
		background-color: #fde2e2;
		color: #f56c6c;
	}

	@media (max-width: 600px) {
		.container {
			padding: 10px;
		}

		h1 {
			font-size: 20px;
		}

		.el-button {
			margin-top: 10px;
			width: 100%;
		}
	}
</style>
